<?php

class JiangQie_API_Part_Controller extends JiangQie_API_Base_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->module = 'part';
	}

	public function register_routes()
	{

		register_rest_route($this->namespace, '/' . $this->module . '/alltype', [
			[
				'callback' => [$this, 'get_all_type'],
			]
		]);
        register_rest_route($this->namespace, '/' . $this->module . '/list', [
            [
                'callback' => [$this, 'get_list'],
            ]
        ]);
        register_rest_route($this->namespace, '/' . $this->module . '/partsdetail', [
            [
                'callback' => [$this, 'get_partsdetail'],
            ]
        ]);

        register_rest_route($this->namespace, '/' . $this->module . '/addpart', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'addpart'],
            ]
        ]);

        register_rest_route($this->namespace, '/' . $this->module . '/detail', [
            [
//                'methods' => 'POST',
                'callback' => [$this, 'detail'],
            ]
        ]);
        register_rest_route($this->namespace, '/' . $this->module . '/get_more_fpv', [
            [
//                'methods' => 'POST',
                'callback' => [$this, 'get_more_fpv'],
            ]
        ]);

	}

	/**
	 * 获取配置 首页
	 */
	public function get_all_type(){
        global $wpdb;
        $parts_type = $wpdb->get_results("select * from parts_type order by type DESC,sort ASC");

        $data['parts_type'] = $parts_type;

		return $this->make_success($data);
	}

	//获取指定类型下的零件
    public function get_list(){
        $start = isset($_GET['start']) ? $_GET['start'] : 0;
        $type = isset($_GET['type']) ? $_GET['type'] : 1;
        $name = isset($_GET['name']) ? trim($_GET['name']) : '';

        return $this->make_success($this->_list($start, $type, $name));
    }

    public function _list($start, $type, $name){

        $limit = $start*12 . ",12";

        $sql = "select * from parts where parts_type_id = {$type} and name like '%{$name}%' order by update_time DESC limit {$limit}";
        global $wpdb;
        $parts = $wpdb->get_results($sql);

        foreach ($parts as $part){
            $part->info_url = site_url()."/category/parts/info/".$part->id.".html";
            if(is_open_cos()){
                $part->img = get_cos_domain().$part->img;
            }else{
                $part->img = site_url().$part->img;
            }
        }

        return $parts;
    }

    public function get_partsdetail(){
	    $id = $_GET['id'];
        global $wpdb;
        $fpv_ids = $wpdb->get_results("select distinct(fpv_id) from fpv_parts where parts_id = {$id} order by update_time DESC");

        $posts = [];

        foreach ($fpv_ids as $fi) {
            $posts[] = $fi->fpv_id;
        }

        $query = new WP_Query();
        $result = $query->query([
            'post_type' => ['post'],
            'post__in' => $posts
        ]);

        $posts = apply_filters('jiangqie_post_for_list', $result);

        foreach ($posts as &$post) {
            //查询tag
            $tags = get_the_tags($post['id']);
            if (!$tags) {
                $post['tags'] = [];
            } else {
                $post['tags'] = apply_filters('jiangqie_tag_for_list', $tags);
            }

            //美化时间
            $post['time'] = $this->time_beautify($post['time']);

            $post['views'] = (int)get_post_meta($post['id'], 'views', true);

            //如果开启了缓存服务，把图片的url替换成cos
            if(is_open_cos()){
                $post['thumbnail'] = replace_cos_url($post['thumbnail']);
            }
        }

        return $this->make_success($posts);
    }

    public function addpart(){


        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: *");
        //CORS
        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');//注意头部自定义参数不要用下划线


        $type = isset($_POST['type']) ? $_POST['type'] : 0;
        $part_name = isset($_POST['name']) ? $_POST['name'] : '';
        $img = isset($_POST['img']) ? $_POST['img'] : '';
        $url = isset($_POST['url']) ? $_POST['url'] : '';
        $price = isset($_POST['price']) ? $_POST['price'] : 0;

        if(!$type || !$part_name || !$img){
            return $this->make_error("type,img,name不能为空");
        }

        //处理url
        if($url){
            $parse_url = parse_url($url);
            parse_str($parse_url['query'],$query_arr);
            if(isset($query_arr['id'])){
                $url = $parse_url['scheme']."://".$parse_url['host'].$parse_url['path']."?id=".$query_arr['id'];
            }
        }

        //下载远程图片
        //生成图片路径
        $path = "/wp-content/uploads/".date("Y/m",time());
        $name = uniqid("parts_").".jpg";
        $path_name = $path .'/'.$name;

        if(substr($img,0,4)=="data"){
            $imageFile = [
                'path' => $path,
                'name' => $name,
                'path_name' => $path_name
            ];
            downloadBase64image($img,$imageFile);
        }
        if(substr($img,0,4)=="http"){

            download_image($img, $path_name);//图片为真，会保留；图片为假，会删除

        }
        //图片如果不存在，则表示已经被download_image函数销毁
        if(!file_exists(ABSPATH.$path_name)){
            return $this->make_error("图片地址不对！");
        }
        //上传到cos
        upload_img_to_cos(ABSPATH.$path_name, $path_name);

        global $wpdb;
        $wpdb->insert('parts',[
            'parts_type_id' => $type,
            'name' => $part_name,
            'img' => $path_name,
            'url' => $url,
            'price' => $price,
            'origin_url' => '自主上传',
            'create_time' => date("Y-m-d H:i:s",time()),
            'update_time' => date("Y-m-d H:i:s",time())
        ]);

        return $this->make_success('添加成功');
    }

    function isImage($imgPath){
        $file  = fopen($imgPath, "rb");
        $bin  = fread($file, 2); // 只读2字节

        fclose($file);
        // 标识前两个字符按照，c格式，数组索引chars1、chars2
        $strInfo = unpack("C2chars", $bin);
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        $fileType = '';

        if($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/) {
            return $typeCode;
        }else {
            return false;
        }
    }

    function detail()
    {
        $id = isset($_GET['id']) ? $_GET['id'] : 0;
        if (!$id) {
            return $this->make_error("配置零件不存在");
        }

        global $wpdb;
        $part = $wpdb->get_row("select parts.id,price,url,img,parts.name as name,parts_type.name as part_name,parts.update_time from parts left join parts_type on parts.parts_type_id = parts_type.id where parts.id = $id");
        if (!$part) {
            return $this->make_error("配置零件不存在");

        }

        if(is_open_cos()){
            $part->img = get_cos_domain() . $part->img;
        }else{
            $part->img = site_url() . $part->img;
        }




        return $this->make_success(['data'=> $part]);
    }

    function get_more_fpv(){
        $id = isset($_GET['id']) ? $_GET['id'] : 0;
        $page = isset($_GET['page']) ? $_GET['page'] : 0; //从0开始
        if (!$id) {
            return $this->make_error("请输入要查询的配件ID");
        }

        $limit = ($page*6).",6";


        global $wpdb;
        $fpv_ids = $wpdb->get_results("select fpv_id from fpv_parts where parts_id = {$id} order by update_time DESC LIMIT {$limit}");

        $fpvs = [];
        if($fpv_ids){
            foreach ($fpv_ids as $k => $fi){
                $postObj = get_post($fi->fpv_id);
                $postObj->thumbnail = is_open_cos() ? replace_cos_url(apply_filters('jiangqie_post_thumbnail', $fi->fpv_id)) : apply_filters('jiangqie_post_thumbnail', $fi->fpv_id);
                $fpvs[] = $postObj;

            }
        }

        return $this->make_success(['data'=>$fpvs]);


    }
	
}
